package com.ifacebox.client.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author znn
 */
public class SspPlaceSearchManager {
    private final SspPlaceSearchConfig config;
    private final OkHttpClient client;

    public SspPlaceSearchManager(SspPlaceSearchConfig config) {
        this.config = config;
        this.client = new OkHttpClient.Builder().build();
    }

    public void searchPlace(String region, String name, String address) throws IOException {
        System.out.printf((SspPlaceSearchConstants.PLACE_SEARCH_URL) + "%n", name, region, config.getAk());
        JSONArray places = this.httpGetObject(String.format(SspPlaceSearchConstants.PLACE_SEARCH_URL, name, region, config.getAk()))
                .getJSONArray(SspPlaceSearchConstants.PLACE_SEARCH_RESULT);
        for (int i = 0; i < places.size(); i++) {
            JSONObject place = places.getJSONObject(i);
            String mName = place.getString(SspPlaceSearchConstants.PLACE_SEARCH_RESULT_NAME);
            if (name == null || !name.equalsIgnoreCase(mName)) {
                continue;
            }
            System.out.printf("%s=%s%n", name, mName);
            String uid = place.getString(SspPlaceSearchConstants.PLACE_SEARCH_RESULT_UID);
            System.out.printf((SspPlaceSearchConstants.PLACE_DETAIL_URL) + "%n", uid, config.getAk());
            JSONObject detail = this.httpGetObject(String.format(SspPlaceSearchConstants.PLACE_DETAIL_URL, uid, config.getAk()))
                    .getJSONObject(SspPlaceSearchConstants.PLACE_SEARCH_RESULT);
            String mAddress = detail.getString(SspPlaceSearchConstants.PLACE_SEARCH_RESULT_ADDRESS);
            if (address != null && address.equalsIgnoreCase(mAddress)) {
                return;
            }
            System.out.printf("%s=%s%n", address, mAddress);
            throw new IOException(String.format("POI地址不匹配【%s】", mAddress));
        }
        throw new IOException("POI名称不匹配");
    }

    public JSONObject httpGetObject(String url) throws IOException {
        try (Response response = client.newCall(new Request.Builder()
                .url(url).build()).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException(response.code() + ":" + response.message());
            }
            JSONObject object = JSON.parseObject(response.body().string());
            if (!SspPlaceSearchConstants.STATUS_OK.equals(object.getString(SspPlaceSearchConstants.PLACE_SEARCH_STATUS))) {
                throw new IOException(object.getString(SspPlaceSearchConstants.PLACE_SEARCH_MESSAGE));
            }
            return object;
        }
    }
}
